package com.fight.strive.sys.modules.scheduler;

import com.fight.strive.sys.modules.scheduler.service.SchJobService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 任务调度控制
 */
@Slf4j
@Getter
@Component
public class Scheduling implements InitializingBean, Runnable {

    /**
     * 控制变量
     */
    private AtomicBoolean start;

    @Resource
    private SchJobService schJobService;

    private final ExecutorService executorService;

    public Scheduling() {
        this.executorService = Executors.newSingleThreadExecutor();
    }

    /**
     * 启动时运行
     */
    @Override
    public void afterPropertiesSet() {
        this.start = new AtomicBoolean(false);
        executorService.submit(this);
    }

    /**
     * 单独线程运行
     */
    @Override
    public void run() {
        while (start.get()) {
            try {
                schJobService.handleJob();
            } catch (Exception e) {
                if (e instanceof RedisConnectionFailureException) {
                    log.error("redis 连接断开...");
                } else {
                    log.error("任务调度异常：", e);
                }
            }
            this.sleep(500);
        }
    }

    /**
     * 延时
     */
    public void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception e) {
            log.error("延时失败");
        }
    }
}
